package leetcode;

import java.util.LinkedList;
import java.util.Stack;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

/**
 * 字符串反转
 *
 * @author 王霄
 * @date 2022/2/7 16:54
 **/
public class ReverseStr {

    public static void main(String[] args) {
        System.out.println(reverse1("java"));
        System.out.println(reverse2("java"));
        System.out.println(reverse3("java"));
        System.out.println(reverse4("java"));
        System.out.println(reverse5("java"));
        System.out.println(reverse6("java"));
        System.out.println(reverse7("java"));
    }

    public static String reverse1(String original) {
        return new StringBuilder(original).reverse().toString();
    }

    public static String reverse2(String original) {
        return new StringBuffer(original).reverse().toString();
    }

    public static String reverse3(String original) {
        StringBuilder reverse = new StringBuilder();
        char[] chars = original.toCharArray();
        for (int i = chars.length - 1; i >= 0; i--) {
            reverse.append(chars[i]);
        }
        return reverse.toString();
    }

    public static String reverse4(String original) {
        StringBuilder reverse = new StringBuilder();
        int length = original.length();
        for (int i = 0; i < length; i++) {
            reverse.append(original.charAt((length - 1) - i));
        }
        return reverse.toString();
    }

    public static String reverse5(String original) {
        return IntStream.range(0, original.length())
                .map(i -> original.length() - 1 - i)
                .mapToObj(original::charAt)
                .map(Object::toString)
                .collect(Collectors.joining(""));
    }

    public static String reverse6(String original) {
        Stack<Character> stack = new Stack<>();
        char[] chars = original.toCharArray();
        for (char c : chars) {
            stack.push(c);
        }
        StringBuilder reverse = new StringBuilder();
        while (!stack.isEmpty()) {
            reverse.append(stack.pop());
        }
        return reverse.toString();
    }

    public static String reverse7(String original) {
        char[] chars = original.toCharArray();
        LinkedList<Character> list = new LinkedList<>();
        for (char c : chars) {
            list.addFirst(c);
        }
        return list.stream()
                .map(Object::toString)
                .collect(Collectors.joining(""));
    }
}
